package name.sraynal.map;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BlankMap {
	
	private URL mapUrl;
	private String outputDir;
	private String filename;
	private static final Pattern IMG_PATTERN = Pattern.compile(".+<img src=\"([^\"]+)\".+");
	
	public BlankMap(URL mapUrl, String outputDir, String filename) {
		super();
		this.mapUrl = mapUrl;
		this.outputDir = outputDir;
		this.filename = filename;
	}
	
	public void getFile() throws IOException {
		
        URLConnection yc = mapUrl.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));

        String inputLine;
        int count = 0;

        while ((inputLine = in.readLine()) != null) { 
        	Matcher matcher = IMG_PATTERN.matcher(inputLine);
        	if (matcher.matches() && (count++ == 2)) {   
        		getImage(new URL(matcher.group(1)));
        	}
        }
	}
	
	private void getImage(URL imageUrl) throws IOException {
		File file = new File(new File(outputDir), this.filename);
		OutputStream os = new FileOutputStream(file);

        URLConnection uc = imageUrl.openConnection();
        InputStream in = uc.getInputStream();
        byte [] cbuf = new byte[1024];
        int read;

        while ((read = in.read(cbuf, 0, 1024)) > 0) {
        	os.write(cbuf,0, read);
        }
        os.close();
	}
}